import os
import concurrent
import shutil
from fastapi import APIRouter, Request, Depends, Body
from sqlalchemy.orm import session
from starlette import status
from Model.community.community import  community_index_pre, community_writer_swiper
from api.middleware import judge_token
from config.comunity import *
from concurrent.futures import ThreadPoolExecutor
import datetime
from Model.default import SessionLocal, get_db

admin=APIRouter(prefix="/admin",tags=["admins"],dependencies=[Depends(judge_token)])
def up_load_file(save_path,file,filename):
        # 实际上在前一步就可以处理了，这里只为方便管理。
        os.makedirs(save_path, exist_ok=True)
        file_path = os.path.join(save_path, filename)
        # 将文件内容写入到本地文件
        with open(file_path, 'wb') as buffer:
            shutil.copyfileobj(file.file, buffer)



@admin.post("/index/rec/f")
async  def deal_index_rec_file(request: Request ):
    """
    目前存在问题,未设置检测文件是否存在在,此处由于文件名编码问题暂置
    :param request:
    :return 0/1
    """
    formdata = await request.form()
    date=formdata.get("date")
    title=formdata.get("title")
    thread = []
    session = SessionLocal()
    image_url=''
    filename=str(int(datetime.datetime.now().timestamp()))
    record=None
    try:
        record = community_index_pre()
        record.create_time=date
        record.date=datetime.datetime.now(datetime.timezone.utc).date()
        record.title=title
        LENGTH=formdata.get('files')

        with ThreadPoolExecutor(max_workers=6) as executer:
            for i in range(int(LENGTH)):
                pre_file=formdata.get('file'+str(i))
                extension=os.path.basename(pre_file.filename).rsplit('.', 1)[1]

                if extension =='txt':
                     os.makedirs(TXT_SAVE_PATH, exist_ok=True)
                     file_path = os.path.join(TXT_SAVE_PATH, filename+'.'+extension)
                    # 将文件内容写入到本地文件
                     record.txt = file_path
                     with open(file_path, 'wb') as buffer:
                        shutil.copyfileobj(pre_file.file, buffer)
                else:
                    image_url+=INDEX_REC_SEND_DIR+filename+ 'file'+str(i)+'.'+extension+'_+_'

                    thread.append(executer.submit(up_load_file,IMAGE_SAVE_PATH, pre_file,filename+'file'+str(i)+'.'+extension))
            for i in concurrent.futures.as_completed(thread):
                pass
        record.images=image_url
        session.add(record)
        session.commit()
    except Exception as e:
        session.rollback()
        if record:
            session.delete(record)
            session.commit()
        return 0
    finally:
        session.close()
    return  1

@admin.post("/index/rec/f_d")
async def deal_index_rec_file_delete(id:int):
    """
    直接根据首页推荐的id进行删除,假删除文件仍然存在
    :param id: 前端获取为uuid
    :return:
    """
    session=SessionLocal()
    try:
      session.query(community_index_pre).filter_by(id=id).delete()
      session.commit()
      return 1
    except Exception as e:
        return 0
        pass
    finally:
        session.close()
@admin.post("/put/writer/index/swiper")
def deal_index_swiper_put(DATA:str=Body(...,embed=True),db:session=Depends(get_db)):
    """
    用于上传写作平台的信息,swiper展示
    :param Type:
    :param DATA:
    :param db:
    :return:
    """
    try:
        data=community_writer_swiper(content=DATA)
        db.add(data)
        db.commit()
        return status.HTTP_200_OK
    except Exception as e:
        print(e)
        db.rollback()
        return status.HTTP_500_INTERNAL_SERVER_ERROR
    finally:
        db.close()

@admin.get("/get/writer/index/swiper")
def deal_get_index_Swiper_input(limit:int=1,db:session=Depends(get_db)):
    try:
        total=db.query(community_writer_swiper).count()
        data =db.query(community_writer_swiper).offset((limit-1)*20).limit(limit).all()
        DATA={
            'total':total,
            'data':data,
            'page':limit
        }
        return DATA
    except Exception as e:
        return status.HTTP_500_INTERNAL_SERVER_ERROR
    finally:
        db.close()


@admin.post("/delete/writer/index/swiper")
def deal_delete_index_Swiper_input(id: int = 1, db: session = Depends(get_db)):
    try:
        db.query(community_writer_swiper).filter_by(id=id).delete()
        db.commit()
        return status.HTTP_200_OK
    except Exception as e:
        return status.HTTP_500_INTERNAL_SERVER_ERROR
    finally:
        db.close()













